package com.promotores;


import java.util.ArrayList;
import java.util.List;
import java.io.IOException;
import java.sql.Date;

import org.json.JSONException;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;

public class GestorPromocion extends CreaTablas{
	CreaTablas db;
	// tipoPromocion table name
	private static final String TABLE_PROMOCION = "Promocion";
    
	// tipoPromocion Table Columns names
	private static final String KEY_ID = "id";
	private static final String KEY_ID_LOCAL = "idLocal";
	private static final String KEY_ID_TIPO_PROMOCION = "idTipoPromocion";
	private static final String KEY_ID_EVENTO = "idEvento";
	private static final String KEY_FECHAINI = "fechaIni";
	private static final String KEY_FECHAFIN = "fechaFin";
	private static final String KEY_DESCUENTO = "descuento";
	private static final String KEY_DIAS = "dias";
	private static final String KEY_FLAG_SAVED = "FlagSaved";
	private static final String KEY_DELETED = "deleted";
	private static final String KEY_CREATED_AT = "created_at";
	private static final String KEY_UPDATED_AT = "updated_at";

	public GestorPromocion(Context context) {
		super(context);
		db = new CreaTablas(context);
	}
	/**
	 * All CRUD(Create, Read, Update, Delete) Operations
	 */

	// Adding new tipoPromocion
	public int addPromocion(BeanPromocion promocion) {
		SQLiteDatabase db = this.getWritableDatabase();
		int idLocal = getNextId();
		System.out.println("idlocal:"+idLocal);
		ContentValues values = new ContentValues();
		values.put(KEY_ID, promocion.getId());
		values.put(KEY_ID_LOCAL, idLocal);
		values.put(KEY_ID_TIPO_PROMOCION, promocion.getTipoPromocion().getId());
		values.put(KEY_ID_EVENTO, promocion.getEvento().getId());
		values.put(KEY_FECHAINI,promocion.getFecIni());
		values.put(KEY_FECHAFIN,promocion.getFecFin());
		values.put(KEY_DESCUENTO, promocion.getDescuento());
		values.put(KEY_DIAS, promocion.getDias());
		values.put(KEY_FLAG_SAVED, promocion.getSaved());
		values.put(KEY_DELETED, promocion.getDeleted());
		values.put(KEY_CREATED_AT, promocion.getCreated_at());
		values.put(KEY_UPDATED_AT, promocion.getUpdated_at());
		
		// Inserting Row
		db.insert(TABLE_PROMOCION, null, values);
		db.close(); // Closing database connection
		return idLocal;
	}

	// Getting single tipoPromocion
	public BeanPromocion getPromocion(int id) {
		SQLiteDatabase db = this.getReadableDatabase();
	
		String selectQuery = "SELECT  * FROM " + TABLE_PROMOCION + " WHERE id = " + id + "";
		Cursor cursor = db.rawQuery(selectQuery, null);
		if (cursor != null)
			cursor.moveToFirst();
		BeanTipoPromocion tipoPromocion = new BeanTipoPromocion();
		tipoPromocion.setId(Integer.parseInt(cursor.getString(2)));
		BeanEvento evento = new BeanEvento();
        evento.setId(Integer.parseInt(cursor.getString(3)));
        BeanPromocion promocion = new BeanPromocion();
		promocion.setId(Integer.parseInt(cursor.getString(0)));
		promocion.setIdLocal(Integer.parseInt(cursor.getString(1)));
		promocion.setTipoPromocion(tipoPromocion);
		promocion.setEvento(evento);
		promocion.setFecIni(cursor.getString(4));
		promocion.setFecFin(cursor.getString(5));
		promocion.setDescuento(Integer.parseInt(cursor.getString(6)));
		promocion.setDias(cursor.getString(7));
		promocion.setSaved(cursor.getString(8));
		promocion.setDeleted(cursor.getString(9));
		promocion.setCreated_at(cursor.getString(10));
		promocion.setUpdated_at(cursor.getString(11));
		// return contact
		db.close();
		return promocion;
	}
	

	// Getting All tipoPromocion
	public List<BeanPromocion> getAllPromocion(int id) {
		List<BeanPromocion> listaPromociones = new ArrayList<BeanPromocion>();
		// Select All Query
		String selectQuery = "SELECT  * FROM " + TABLE_PROMOCION + " WHERE " + KEY_ID_EVENTO + " = " + id + " AND " +  KEY_DELETED + " <> " + "1";

		SQLiteDatabase db = this.getWritableDatabase();
		Cursor cursor = db.rawQuery(selectQuery, null);

		// looping through all rows and adding to list
		if (cursor.moveToFirst()) {
			do {
				BeanTipoPromocion tipoPromocion = new BeanTipoPromocion();
				tipoPromocion.setId(Integer.parseInt(cursor.getString(2)));
				BeanEvento evento = new BeanEvento();
		        evento.setId(Integer.parseInt(cursor.getString(3)));
		        BeanPromocion promocion = new BeanPromocion();
				promocion.setId(Integer.parseInt(cursor.getString(0)));
				promocion.setIdLocal(Integer.parseInt(cursor.getString(1)));
				promocion.setTipoPromocion(tipoPromocion);
				promocion.setEvento(evento);
				promocion.setFecIni(cursor.getString(4));
				promocion.setFecFin(cursor.getString(5));
				promocion.setDescuento(Integer.parseInt(cursor.getString(6)));
				promocion.setDias(cursor.getString(7));
				promocion.setSaved(cursor.getString(8));
				promocion.setDeleted(cursor.getString(9));
				promocion.setCreated_at(cursor.getString(10));
				promocion.setUpdated_at(cursor.getString(11));
				// Adding tipoPromocion to list
				listaPromociones.add(promocion);
			} while (cursor.moveToNext());
		}
		db.close();
		// return tipoPromocion list
		return listaPromociones;
	}
	
	// Getting All tipoPromocion
	public List<BeanPromocion> getAllPromocionNotSaved() {
		List<BeanPromocion> listaPromociones = new ArrayList<BeanPromocion>();
		// Select All Query
		String selectQuery = "SELECT  * FROM " + TABLE_PROMOCION + " WHERE " + KEY_FLAG_SAVED + " = '0'";

		SQLiteDatabase db = this.getWritableDatabase();
		Cursor cursor = db.rawQuery(selectQuery, null);

		// looping through all rows and adding to list
		if (cursor.moveToFirst()) {
			do {
				BeanTipoPromocion tipoPromocion = new BeanTipoPromocion();
				tipoPromocion.setId(Integer.parseInt(cursor.getString(2)));
				BeanEvento evento = new BeanEvento();
		        evento.setId(Integer.parseInt(cursor.getString(3)));
		        BeanPromocion promocion = new BeanPromocion();
				promocion.setId(Integer.parseInt(cursor.getString(0)));
				promocion.setIdLocal(Integer.parseInt(cursor.getString(1)));
				promocion.setTipoPromocion(tipoPromocion);
				promocion.setEvento(evento);
				promocion.setFecIni(cursor.getString(4));
				promocion.setFecFin(cursor.getString(5));
				promocion.setDescuento(Integer.parseInt(cursor.getString(6)));
				promocion.setDias(cursor.getString(7));
				promocion.setSaved(cursor.getString(8));
				promocion.setDeleted(cursor.getString(9));
				promocion.setCreated_at(cursor.getString(10));
				promocion.setUpdated_at(cursor.getString(11));
				// Adding tipoPromocion to list
				listaPromociones.add(promocion);
			} while (cursor.moveToNext());
		}
		db.close();
		// return tipoPromocion list
		return listaPromociones;
	}

	// Updating single tipoPromocion
	public void updatePromocion(BeanPromocion promocion) {
		SQLiteDatabase db = this.getWritableDatabase();
		db.execSQL("UPDATE " + TABLE_PROMOCION + " SET " + KEY_UPDATED_AT + " = '" + promocion.getUpdated_at() + "', " 
		+ KEY_DELETED + " = '" + promocion.getDeleted() + "' WHERE " + KEY_ID + " = " + promocion.getId()); 
		db.close();
	}
	
	

	// Deleting single Promocion
	public void deletePromocion(BeanPromocion promocion) {
		SQLiteDatabase db = this.getWritableDatabase();
		db.delete(TABLE_PROMOCION, KEY_ID + " = ?" + "AND" + KEY_ID_EVENTO + " = ?",
				new String[] { String.valueOf(promocion.getTipoPromocion().getId()), String.valueOf(promocion.getEvento().getId())});
		db.close();
	}

	public void deleteAll(){
		SQLiteDatabase db = this.getWritableDatabase();
		db.execSQL("DELETE FROM " + TABLE_PROMOCION);	
		db.close();
	}
	
	public void deleteFisicoById(int id){
		SQLiteDatabase db = this.getWritableDatabase();
		db.execSQL("DELETE FROM " + TABLE_PROMOCION + " WHERE idLocal = " + id);	
		db.close();
	}
	
	public void deletebyId(int id){
		SQLiteDatabase db = this.getWritableDatabase();
		String consulta = "UPDATE " + TABLE_PROMOCION 
						  + " SET " + KEY_DELETED + " = " 
						  + "1" 
						  + " WHERE " + KEY_ID + " = " + id + ";";
		db.execSQL(consulta);
		db.close();
//		SQLiteDatabase db = this.getWritableDatabase();
//		db.execSQL("DELETE FROM " + TABLE_PROMOCION + " WHERE " + KEY_ID +" = " + id + ";");	
//		db.close();
	}
	
	public int getNextId(){
		int id_aux; 
		String selectQuery = "SELECT MAX(idLocal) FROM " + TABLE_PROMOCION + ";";
		SQLiteDatabase db = this.getReadableDatabase();
		Cursor cursor = db.rawQuery(selectQuery, null);
		if (cursor != null)
			cursor.moveToFirst();
		if (cursor.getString(0) == null){
			cursor.close();
			return 1;
		}
		id_aux = Integer.parseInt(cursor.getString(0))+1;
		cursor.close();
		//db.close();
		return id_aux;
	}
	
	// Getting tipoPromocion Count
	public int getPromocionCount() {
		int contador;
		String countQuery = "SELECT  * FROM " + TABLE_PROMOCION;
		SQLiteDatabase db = this.getReadableDatabase();
		Cursor cursor = db.rawQuery(countQuery, null);
		contador = cursor.getCount();
		cursor.close();
		db.close();
		// return count
		return contador;
	}
	
	public void setSaved(BeanPromocion promocion){
		SQLiteDatabase db = this.getWritableDatabase();
		db.execSQL("UPDATE " + TABLE_PROMOCION + " SET " + KEY_FLAG_SAVED + " = 1 WHERE " + KEY_ID_LOCAL + " = " + promocion.getIdLocal()); 
		db.close();
	}

	public void setId(BeanPromocion promocion){
		SQLiteDatabase db = this.getWritableDatabase();
		db.execSQL("UPDATE " + TABLE_PROMOCION + " SET " + KEY_ID + " = " + promocion.getId() + " WHERE " + KEY_ID_LOCAL + " = " + promocion.getIdLocal()); 
		db.close();
	}
	
	public void setSavedbyId(int id, String flag){
		SQLiteDatabase db = this.getWritableDatabase();
		db.execSQL("UPDATE " + TABLE_PROMOCION + " SET " + KEY_FLAG_SAVED + " = " + flag + " WHERE " + KEY_ID + " = " + id); 
		db.close();
	}
	
	public int verificarRegistro(int idEv, int idTipoPro, String fechaIni, String fechaFin){
		String countQuery = "SELECT  * FROM " + TABLE_PROMOCION + " WHERE " + KEY_ID_TIPO_PROMOCION + "=" + idTipoPro +
				             " AND " + KEY_ID_EVENTO + "=" + idEv + " AND (('" + fechaIni  + "'>=" + KEY_FECHAINI + " AND '" + 
				              fechaIni  + "'<=" + KEY_FECHAFIN + ")" + "OR" + "('" + fechaFin  + "'>=" + KEY_FECHAINI + " AND '" + 
				              fechaFin  + "'<=" + KEY_FECHAFIN + "))" + ";";
		SQLiteDatabase db = this.getReadableDatabase();
		Cursor cursor = db.rawQuery(countQuery, null);
		int count = cursor.getCount();
		cursor.close();
		
		return count;
	}
	
	public void syncData() {
		List<BeanPromocion> listaPromocion = getAllPromocionNotSaved();
		JsonPromocion jPromocion = new JsonPromocion(); 
		for (int i=0; i<listaPromocion.size(); i++){			
			if (listaPromocion.get(i).getDeleted().compareTo("0") == 0){
			//agregar
				try{
					BeanPromocionResponse result = jPromocion.postData(listaPromocion.get(i));
					if (result!=null) {
						listaPromocion.get(i).setId(result.getId());
						listaPromocion.get(i).setUpdated_at(result.getUpdated_at());
						listaPromocion.get(i).setCreated_at(result.getCreated_at());
						setId(listaPromocion.get(i));
						setSaved(listaPromocion.get(i));
						setFechas(listaPromocion.get(i));
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			else{
				//eliminar
				try {
					int result = jPromocion.postDeleted(listaPromocion.get(i).getId());
					if (result!=0) setSavedbyId(listaPromocion.get(i).getId(), "1");	
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	public void setFechas(BeanPromocion promocion) {
		// TODO Auto-generated method stub
		SQLiteDatabase db = this.getWritableDatabase();
		db.execSQL("UPDATE " + TABLE_PROMOCION + " SET " + KEY_UPDATED_AT + " = '" + promocion.getUpdated_at() + "', " + KEY_CREATED_AT + " = '" + promocion.getCreated_at() + "' WHERE " + KEY_ID + " = " + promocion.getId()); 
		db.close();
	}
	
	public int getPromocionExiste(int idServer){
		String countQuery = "SELECT  * FROM " + TABLE_PROMOCION + " WHERE id ="+idServer+";";
		SQLiteDatabase db = this.getReadableDatabase();
		Cursor cursor = db.rawQuery(countQuery, null);
		int count = cursor.getCount();
		cursor.close();
		db.close();
		return count;
	}

}